package com.shop.merchant.messageHandle;

import com.alibaba.fastjson.JSONObject;
import com.shop.merchant.po.RedisLogic.RedisData;
import com.shop.po.dto.GoodsInfo;
import com.shop.merchant.service.GoodsBaseService;
import com.shop.po.Message;
import com.shop.service.MessageProcessAbstract;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author 'banxia'
 * @version 1.0
 * @description 用于接收xxl-job发配的任务，然后从消息表中取出数据并执行
 * @date 2023/2/25 0:55
 */
@Slf4j
@Component
public class GoodsPublishHandle extends MessageProcessAbstract {


    private static final int count=4;

    //过期时间：1小时
    private Long expireTime=60*60L;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsBaseService goodsBaseService;

    @XxlJob("goodsPublic")
    public void goodsPublicTask(){
        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        process(shardIndex,shardTotal,
                "goodsPublic",
                count,
                10);
    }


    //执行的具体实现，状态1，状态2。。。。
    @Override
    public boolean execute(Message message) {
//        if (mqMessageService.getStageOne(message.getId()))
        try {
            int over = getMqMessageService().getStageOne(message.getId());
            if (over==1){
                System.out.println("已经完成");
            }else{
                //完成第一阶段任务
                saveToRedis(Long.parseLong(message.getBusinessKey1()));
                getMqMessageService().completedStageOne(message.getId());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            log.error("任务执行失败");
            return false;
        }
        return true;
    }


    //查询商品然后储存到redis（第一阶段任务）
    public void saveToRedis(Long id){
        //(1)获取商品数据
        log.info("================================================");
        log.info("开始获取商品数据");
        log.info("================================================");
        GoodsInfo goodsInfo = goodsBaseService.getByGoodsIdFromDb(id);
        //（2）封装为redis数据
        RedisData redisData=new RedisData();
        redisData.setData(goodsInfo);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        //（3）储存到redis
        String redisDataJson = JSONObject.toJSONString(redisData);
        redisTemplate.opsForValue().set("goods:"+id,redisDataJson);
        log.info("================================================");
        log.info("已将商品id为:{}缓存到redis中",id);
        log.info("================================================");

    }

}
